module.exports = (app) => {
  const mongoose = app.mongoose;
  mongoose.pluralize(null);
  const Schema = mongoose.Schema;
  const GoodsSchema = new Schema(
    {
      // 商品类型，1：一般商品，2：小料
      type: {
        type: Number,
        default: 1
      },
      // 分类id
      categoryId: {
        type: mongoose.Types.ObjectId,
        ref: "Category", //关联到分类集合
        required: true,
      },
      // 商品标签
      label: {
        type: [String],
        default:[]
      },
      // 商品图片
      image: {
        type: String,
        required: true,
      },
      // 商品名称
      name: {
        type: String,
        required: true,
      },
      // 商品描述
      description: {
        type: String,
        required: true,
      },
      // 商品最低价格
      price: {
        type: Number,
        required: true,
      },
      // 商品库存
      stock: {
        type: Number,
        required: true,
      },
      // 是否推荐
      recommend: {
        type: Boolean,
        default: false,
      },
      // 销量
      saleNum: {
        type: Number,
        default: 0,
      },
      //   商品属性（有多个，规格，甜度，温度之类）
      attribute: [{
        parentId: { type: String, default: null },
        label: { type: String, required: true },
        sort: { type: Number, default: 0 },
        minAddPrice: { type: Number, default: 0 },
        recommend: { type: Boolean, default: false },
        children: [{
          label: { type: String, required: true }, //子属性名称
          _id: mongoose.Types.ObjectId,
          parentId: mongoose.Types.ObjectId,
          sort: { type: Number, default: 0 },
          addPrice: { type: Number, default: 0 },//加价
          recommend: { //是否推荐
            type: Boolean,
            default: false,
          },
        },]
      }],
      checkedkeys:{
        type:[mongoose.Types.ObjectId],
        default:[]
      }, //前端树形组件选中key
      // 小料
      small: {
        type: [{ _id: String, name: String }]
      }
    },
    { versionKey: false, timestamps: true }
  );
  GoodsSchema.pre("save", function(next){
    console.log(this.name,this.selectedkeys);
    if (this.recommend) {
      this.label.push("老板推荐")
    }
    next();
  })
  return mongoose.model("Goods", GoodsSchema);
};
